/**
 * Created by admin on 14-9-10.
 */
if(typeof (module) !="undefined"){
    module.exports = StyleProcessor;

    var ImageObj = require('../obj/ImageObj');
    var Effect = require('./Effect');
    var config = require('../../config').getConfig();
    var im = require('imagemagick'); // 图像处理
    var common = require('../../common');
    var fs = require('fs');

}

function StyleProcessor(){

}
/**
 * 根据图片的imgFilter类型取得变换矩阵
 * @param type  ：imgFilter类型
 * @return 返回null表示没有图像滤镜， 否则返回6x6矩阵，
 *          矩阵变换量分别为（单位是百分比）：'Red', 'Green', 'Blue', 'Black' (可选), 'Alpha'(可选),'Offset'(可选)
 */
StyleProcessor.prototype.getMatrixByType = function(type){
    var MAX_COLOR_VALUE = 255.0;
    if(type == Effect.prototype.IMAGE_FILTER_NONE){
        return null;
    }else if(type == Effect.prototype.IMAGE_FILTER_OLD){
        //第一种特效 ：老照片
        return  [
            [0.5, 0.59, 0.11,0, 0, 0],
            [0.4, 0.59, 0.11,0, 0, 0],
            [0.16, 0.59, 0.11,0, 0, 0],
            [0,0,0,1,0,0],
            [0,0,0,0,1,0],
            [0,0,0,0,0,1]
        ];
    }
    else if(type == Effect.prototype.IMAGE_FILTER_BLACKWHITE){
        //第二种特效 ：黑白
        return [
            [0.2225,0.7196,0.0606,0,0,0],
            [0.2225,0.7196,0.0606,0,0,0],
            [0.2225,0.7196,0.0606,0,0,0],
            [0,0,0,1,0,0],
            [0,0,0,0,1,0],
            [0,0,0,0,0,1]
        ];


    }
    else if(type == Effect.prototype.IMAGE_FILTER_INCREASING){
        //第三种特效 ：增强
        return  [
            [1.3,0,0,0,0,-128*0.3/MAX_COLOR_VALUE],
            [0,1.3,0,0,0,-128*0.3/MAX_COLOR_VALUE],
            [0,0,1.3,0,0,-128*0.3/MAX_COLOR_VALUE],
            [0,0,0,1,0,0],
            [0,0,0,0,1,0],
            [0,0,0,0,0,1]
        ];

    }
    else if(type == Effect.prototype.IMAGE_FILTER_WHITENING){
        //第四种特效 ：皮肤美白(可能有问题，需要调查)
        var r = 0xFFF0F5>> 16 & 0xFF;
        var g = 0xFFF0F5>> 8 & 0xFF;
        var b = 0xFFF0F5 & 0xFF;
        return  [
            [r/225, 0, 0,0, 0,0],
            [0,g/225, 0, 0,0, 0],
            [0, 0, b/225 ,0, 0, 0],
            [0,0,0,1,0,0],
            [0,0,0,0,1,0],
            [0,0,0,0,0,1]
        ];

    }
    else if(type == Effect.prototype.IMAGE_FILTER_INVERSE){
        //第五种特效 ：反色
        return  [
            [-1,0,0,0,0,1],
            [0,-1,0,0,0,1],
            [0,0,-1,0,0,1],
            [0,0,0,1,0,0],
            [0,0,0,0,1,0],
            [0,0,0,0,0,1]
        ];

    }
    else if(type == Effect.prototype.IMAGE_FILTER_PAPERBW){
        //第六种特效 ：黑白报纸(可能有问题，需要调查)
        return  [
            [ 0.3086*256,0.6094*256,0.0820*256,0,0,-256*140/MAX_COLOR_VALUE],
            [ 0.3086*256,0.6094*256,0.0820*256,0,0,-256*140/MAX_COLOR_VALUE],
            [ 0.3086*256,0.6094*256,0.0820*256,0,0,-256*140/MAX_COLOR_VALUE],
            [0,0,0,1,0,0],
            [0,0,0,0,1,0],
            [0,0,0,0,0,1]
        ];

    }else{
        //第七种特效 ：对比(可能有问题，需要调查)
        return  [
            [2,0,0,0,0,-128/MAX_COLOR_VALUE],
            [0,2,0,0,0,-128/MAX_COLOR_VALUE],
            [0,0,2,0,0,-128/MAX_COLOR_VALUE],
            [0,0,0,1,0,0],
            [0,0,0,0,1,0],
            [0,0,0,0,0,1]
        ];
    }

}
/**
 * 处理图片滤镜，并将图片对象里面的网络路径替换为（带特效的）物理路径
 * @param imageObj  图片对象
 * @param callback  处理完成后的回调函数  (参数：待删除文件的路径，可以为null)
 */
StyleProcessor.prototype.processImageFilter = function(imageObj,callback){
    // 图片网络路径 转换为 物理路径
    var style = imageObj.style();
    var realPath = __dirname+"/../../../ImageServer/public"+imageObj.fp.replace(config.IMAGE_HOST, "");
    var type = imageObj.imgFilter();
    var matrixType = StyleProcessor.prototype.getMatrixByType(type);
    var p = realPath.lastIndexOf('.');
    var a_2_r = Math.PI/180;                                  //角度转换为弧度
    var filterImgPath = realPath.substring(0,p)+'_'+type+'_'+common.genTimeRandom()+realPath.substring(p);
    if(!type || type == Effect.prototype.IMAGE_FILTER_NONE){
        imageObj.fp = realPath;
        callback();
    }
    else{
//        gm(realPath)
//            .recolor(matrixType)
//            .write(filterImgPath,function(err){
//                if (!err) console.log('done');
//                imageObj.fp = filterImgPath;
//                callback(imageObj.fp);
//            });
        var paras = new Array();
        paras.push(realPath);
        paras.push('-recolor');
        paras.push(matrixType);
        paras.push('-define');
        paras.push('png:color-type=6');
        paras.push(filterImgPath);
        paras.join(' ');
        im.convert(paras,function(err){
            if(err) throw err;
            imageObj.fp = filterImgPath;
            callback(imageObj.fp);
        })
    }
}
/**
 * 生成图片阴影效果，并将图片对象里面的网络路径替换为（带特效的）物理路径
 * @param imageObj  图片对象
 * @param callback  处理完成后的回调函数传递以下参数
 *                          path:生成的临时文件，需要删除，可以为null
 *                          shadowImage:新生成的阴影ImageObj，需要放在其from的下方。可以为null
 */
StyleProcessor.prototype.createShadowImageObj = function(imageObj,callback){
    var style = imageObj.style();
    var realPath = imageObj.fp;
    var p = realPath.lastIndexOf('.');
    var a_2_r = Math.PI/180;                                  //角度转换为弧度
    var type = imageObj.imgFilter();
    var filterImgPath = realPath.substring(0,p)+'_'+type+'_'+common.genTimeRandom()+realPath.substring(p);
    if(style){
        var shadowImage = new ImageObj();
        shadowImage.x = imageObj.x;
        shadowImage.y = imageObj.y
        shadowImage.w = imageObj.w;
        shadowImage.h = imageObj.h;
        shadowImage.from = imageObj;
        shadowImage.fp = imageObj.fp;
        // 取得原图的宽高
        var distance = style.d;
        var angle = style.an;
        var color = style.clr.toFormatRGBStr();
        var alpha = 100*style.al;                        //alpha取值为(0,1),ImageMagic单位是百分比
        var blurX = style.bx;
        var xOffset = distance*Math.cos(angle*a_2_r);
        var yOffset = distance*Math.sin(angle*a_2_r);
        var s = ""+alpha+"x"+blurX;
        // 拼接命令，生成图片阴影
        var paras = new Array();
        paras.push(realPath);
        paras.push('-background');
        paras.push(color);
        paras.push('-shadow');
        paras.push(s);
        //当滤镜为黑白效果以及带透明度的图片会导致pdfkit出错，需要将生成的图片模式由灰度图转换成RGB图
        paras.push('-define');
        paras.push('png:color-type=6')//color-type = 6 表示的为颜色类型为RGB色
        paras.push(filterImgPath);
        paras.join(' ');
        im.convert(paras,function(err){
            if(err) throw err;
            shadowImage.x = shadowImage.x+xOffset;
            shadowImage.y = shadowImage.y+yOffset;
            shadowImage.fp = filterImgPath;
            callback(shadowImage.fp,shadowImage);
        });
    }else{
        imageObj.fp = realPath;
        callback();
    }
}
